package com.crl.map.controller
{
	import com.crl.gClient.Player;
	import com.crl.gClient.state.action.WalkAction;
	import com.crl.game.simulation.client.ActorProxy;
	import com.crl.manager.IResizeable;
	import com.crl.manager.ResizeableManager;
	import com.crl.map.view.creater.ItemCreater;
	import com.crl.map.model.MapModel;
	import com.crl.map.model.TileSystem;
	import com.crl.map.utils.astar.AstarFinder;
	import com.crl.map.view.MapCanvas;
	import com.crl.map.view.diy.NodeGenerator;
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class MapController implements IResizeable
	{
		public var model:MapModel;
		
		private var view:MapCanvas;
		
		private var tileSystem:TileSystem;
		
		private var node:NodeGenerator;
		
		
		public var hero:Player;
		
		private var astarFinder:AstarFinder;
		public function MapController()
		{
			view=new MapCanvas();
			view.getTrigger().addEventListener(MouseEvent.MOUSE_UP,mouseHandler);
		}
		
		
		public function resize(w:int,h:int):void{
			view.x=(w-model.getWidth())>>1;
			view.y=(h-model.getHeight())>>1;
		}
		
		
		public function setModel(value:MapModel):void{
			model=value;
			node=new NodeGenerator(value);
			astarFinder=new AstarFinder(node);
			render();
			ResizeableManager.getInstance().add(this);
		}
		
		
		public function addActorProxy(actor:ActorProxy):void{
			view.thingLayer.addChild(actor.getView());
		}
		
		public function getActorProxy():ActorProxy{
			return null;
		}
		
		private function render():void{
			
			node.drawGrid(view.floorGraphics);
			node.drawTrigger(view.triggerGraphics);
			
			
			var code:int;
			var item:DisplayObject
			for (var i:int=0;i<model.length;i++){
				code=model.getIndex(i);
				
				item=ItemCreater.create(code);
				if(item){
					item.x=i%model.col*model.tw;
					item.y=int(i/model.col)*model.th;
					view.thingLayer.addChild(item);
				}
			}	
			
		}
		
		public function getView():DisplayObject{
			return view;
		}
		
		private function mouseHandler(event:MouseEvent):void{
			var x:int=event.localX;
			var y:int=event.localY;
			
			var ix:int=Math.floor(x/model.tw);
			var iy:int=Math.floor(y/model.th);
			
			astarFinder.find(new Point(),new Point(ix,iy));
			
			var path:Array=[];
			hero.requestAction(new WalkAction(path));
		}
		
	}
}